// 文件改变
function fileChanged(element){
	var inputFile = document.getElementById('inputFile');
	var file = inputFile.files[0];
	handleFile(file);
}

// 处理文件
function handleFile(file) {
	// 创建文件读取器
	var fileReader = new FileReader();
	// 监听
    fileReader.onload = function(ev) {
        try {
            var data = ev.target.result
            // 以二进制流方式读取得到整份excel表格对象
            var workbook = XLSX.read(data, { type: 'binary' }) 
            // 获取工作簿1 
        	var sheet1 = workbook.Sheets['Sheet1'];
        	// 班级编号
        	var class_num = sheet1['M1'] && sheet1['M1'].v;
        	// 检测班级编号
        	if (!class_num) {
        		alert('班级编号不能为空');
        		return;
        	}
        	// 学生来源
        	var origin_id = sheet1['N1'] && sheet1['N1'].v;
        	// 学生来源不能为空
        	if (!origin_id) {
        		alert('学生来源不能为空');
        		return;
        	}
        	// 判断范围
        	var sheetRef = sheet1['!ref'];
        	// 长度
        	var length = sheetRef.split(':')[1].substring(1);
        	// 遍历
        	for (var i = 4; i <= length; i++) {
        		// 姓名
        		var name = sheet1['B' + i] && sheet1['B' + i].v;
        		// 用户名为控制停止循环
        		if (name == undefined || name == '') {
        			break;
        		}
        		// 创建学生
        		var student = {
	                "name": name,
	                "sex": sheet1['C' + i].v,
	                "birthday": sheet1['E' + i].v,
	                "national": sheet1['D' + i].v,
	                "mobile": sheet1['I' + i].v,
	                "idcard": sheet1['F' + i].v,
	                "address": sheet1['H' + i].v,
	                "workOrganization": sheet1['H' + i].v,
	                "classNum": class_num,
	                "originId": origin_id,
	                "userImageUrl": ''
        		}
        		// 生日列表
        		var birthday_list = student.birthday.toString().split('.');
                console.log(birthday_list.length);
        		// 生日能够正常分割,说明格式正确
        		if (birthday_list.length == 3) {
        			// 生日
					student.birthday = birthday_list[0] + '-' + formatTwoNumber(birthday_list[1]) + '-' + formatTwoNumber(birthday_list[2]);
					uploadStudent(student, i==length);
					// 延时500ms
					sleep(500);
        		} else {
        			console.log('上传失败: ' + JSON.stringify(student));
        		}
        	}
        } catch (e) {
        	console.log(e);
            // console.log('文件类型不正确');
            return;
        }
    };
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(file);
}

// 将数字格式话为2位
function formatTwoNumber(num) {
	if (num.length == 1) {
		return '0'+num;
	}
	return num;
}

// var xhr = null;

// 上传学生
// @param student 学生
// @param isLast 标记是否为最后一个
function uploadStudent(student, isLast) {
	// if (xhr == null) {
	// 	xhr = new XMLHttpRequest();
	// }
	var xhr = new XMLHttpRequest();
	xhr.open('post', '/fire/student/insertStudent');
	xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	xhr.onreadystatechange = function () {
		if (xhr.readyState === 4 && ( xhr.status === 200 || xhr.status === 304 )){
			var response = JSON.parse(xhr.responseText);
			if (response.error_code == 200) {
				// 添加成功
				console.log('添加成功');
				if (isLast) {
					alert('添加完成');
				}
			} else {
				console.log('添加失败: ' + JSON.stringify(student));
			}
		}
	}
	// 数据
	var data = 'name=' + student.name + '&sex=' + student.sex + '&birthday=' + student.birthday +
		 '&national=' + student.national + '&mobile=' + student.mobile + '&idcard=' + student.idcard + 
		 '&address='+ student.address + '&workOrganization=' + student.workOrganization + 
		 '&classNum=' + student.classNum + '&originId='+ student.originId + 
		 '&userImageUrl=' + student.userImageUrl;
	xhr.send(data);
}

// 延时函数
function sleep(time) {
    var startTime = new Date().getTime() + parseInt(time, 10);
    while(new Date().getTime() < startTime) {}
};